<template>
  <div class="url-picture-upload">
    <div class="upload-box">
      <!-- URL 输入框 -->
      <a-input
        v-model:value="fileUrl"
        class="input-field"
        placeholder="请输入图片 URL"
        allow-clear
        @keyup.enter="handleUpload"
      />
      <!-- 提交按钮 -->
      <a-button
        type="primary"
        class="submit-btn"
        :loading="loading"
        :disabled="!fileUrl"
        @click="handleUpload"
      >
        提交
      </a-button>
    </div>

    <!-- 预览图片 -->
    <div v-if="picture?.url" class="preview-box">
      <img :src="picture.url" alt="图片预览" class="preview-img" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import { uploadPictureByUrlUsingPost } from '@/api/pictureController.ts';

interface Props {
  picture?: API.PictureVO
  spaceId?: number
  onSuccess?: (newPicture: API.PictureVO) => void
}

const props = defineProps<Props>();

const loading = ref<boolean>(false);
const fileUrl = ref<string>('');

/**
 * 上传
 */
const handleUpload = async () => {
  if (!fileUrl.value) {
    message.warning('请输入图片 URL');
    return;
  }

  loading.value = true;
  try {
    const params: API.PictureUploadRequest = { fileUrl: fileUrl.value };
    params.spaceId = props.spaceId;
    if (props.picture) {
      params.id = props.picture.id;
    }
    const res = await uploadPictureByUrlUsingPost(params);
    if (res.data.code === 0 && res.data.data) {
      message.success('图片上传成功');
      props.onSuccess?.(res.data.data);
    } else {
      message.error('图片上传失败，' + res.data.message);
    }
  } catch (error) {
    message.error('图片上传失败');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
/* 组件容器 */
.url-picture-upload {
  width: 100%;
  max-width: 450px;
  margin: 20px auto;
  padding: 16px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
}

/* 上传区域 */
.upload-box {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

/* 输入框 */
.input-field {
  flex: 1;
  height: 40px;
  border-radius: 8px;
  transition: all 0.3s;
}

.input-field:focus {
  border-color: #1890ff;
  box-shadow: 0 0 5px rgba(24, 144, 255, 0.5);
}

/* 提交按钮 */
.submit-btn {
  height: 40px;
  border-radius: 8px;
  font-weight: bold;
  transition: all 0.3s;
}

.submit-btn:disabled {
  background: #ccc !important;
  cursor: not-allowed;
}

/* 预览框 */
.preview-box {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background: #f9f9f9;
  margin-top: 12px;
}

/* 预览图片 */
.preview-img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}
</style>
